/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;

import DAO.CustomersDAO;
import BLO.OrderBLO;
import DTO.Customers.Customer;
import DTO.Customers.Customers;
import DTO.Order.Order;
import DTO.Order.OrderDetail;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import util.Constants;
import util.SupportUtil;

/**
 *
 * @author ThanhTai
 */
public class CustomerController extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException{
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            request.setCharacterEncoding("UTF-8");
            HttpSession session = request.getSession();
            String action = (String) request.getParameter("action");
            if (action.equals("login")) {
                String username = request.getParameter("username");
                String password = request.getParameter("password");
                CustomersDAO dao = new CustomersDAO();
                Customers customers = dao.checkCustomerLogin(username, password);
                if (customers != null && customers.getCustomer() != null) {
                    SupportUtil util = new SupportUtil();
                    String checkLogin = util.marshalReturnString(customers);
                    session.setAttribute("USER", customers.getCustomer().get(0));
                    response.setContentType("text/xml");
                    response.setHeader("Cache-Control", "no-cache");
                    response.getWriter().write(checkLogin);
                }
            } else if (action.equals("logout")) {
                session.removeAttribute("USER");
            } else if (action.equals("checkLoginFinish")) {
                Customer user = (Customer) session.getAttribute("USER");
                if (user != null) {
                    out.print("true");
                } else {
                    out.print("false");
                }
            } else if (action.equals("logout")) {
                session.removeAttribute("USER");
                out.print("true");
            } else if (action.equals("orderCart")) {
                Customer customer = (Customer) session.getAttribute("USER");
                String path = getServletContext().getRealPath("/");
                String xmlPathCart = path + "xml/cart_"+ customer.getCustEmail().trim() +".xml";
                String xmlPathUser = path + "xml/user_"+ customer.getCustEmail().trim() + ".xml";

                //create xml file cart
                String context = request.getParameter("xmlContext");
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();
                Document doc = db.parse(new InputSource(new StringReader(context)));
                TransformerFactory tff = TransformerFactory.newInstance();
                Transformer trans = tff.newTransformer();
                trans.setOutputProperty(OutputKeys.INDENT, "yes");
                Source src = new DOMSource(doc);
                Result rs = new StreamResult(xmlPathCart);
                trans.transform(src, rs);

                //create xml file for user
                Customers customers = new Customers();
                customers.addCustomer(customer);
                SupportUtil util = new SupportUtil();
                util.marshal(xmlPathUser, customer);

                //create order
                Order order = new Order();
                order.setCustEmail(customer.getCustEmail());
                order.setStatus(Constants.OrderStatus_New);
                order.setDate(new Date().getTime());
                order.setDescription("Description automatic!");
                long orderTotal = 0;
                //add cart to database
                NodeList casts = doc.getFirstChild().getChildNodes();
                for (int i = 0; i < casts.getLength(); i++) {
                    Node cast = casts.item(i);
                    OrderDetail od = new OrderDetail();
                    NodeList castInfo = cast.getChildNodes();
                    for (int j = 0; j < castInfo.getLength(); j++) {
                        Node no = castInfo.item(j);
                        if (no.getNodeName().trim().equals("productId")) {
                            od.setProductID(Integer.parseInt(no.getTextContent().trim()));
                        } else if (no.getNodeName().trim().equals("quantity")) {
                            od.setQuantity(Integer.parseInt(no.getTextContent().trim()));
                        } else if (no.getNodeName().trim().equals("subtotal")) {
                            orderTotal = orderTotal + Long.parseLong(no.getTextContent().trim());
                        } else if (no.getNodeName().trim().equals("name")) {
                            od.setProductName(no.getTextContent().trim());
                        } else if (no.getNodeName().trim().equals("price")) {
                            od.setProductPrice(Integer.parseInt(no.getTextContent().trim()));
                        }
                    }
                    order.addOrderDetail(od);
                    //update sold for product
                }
                order.setTotal(orderTotal);
                OrderBLO blo = new OrderBLO();
                if (blo.InsertOrder(order)) {
                    out.print("true");
                } else {
                    out.print("false");
                }
            }
        } catch (SAXException ex) {
            Logger.getLogger(CustomerController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(CustomerController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (TransformerException ex) {
            Logger.getLogger(CustomerController.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
